//
//  NetworkHandle.m
//  王宇先_20_网络数据请求
//
//  Created by 王宇先 on 16/4/6.
//  Copyright © 2016年 王宇先. All rights reserved.
//

#import "NetworkHandle.h"

@interface NetworkHandle ()
@property (nonatomic, assign)id<NetworkHandleDelegate>delegate;

@end



@implementation NetworkHandle
+(void)networkWithURL:(NSString *)urlString delegate:(id<NetworkHandleDelegate>)delegate{
    //Core API
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:urlString];
    //session 中添加 task 任务
    NSURLSessionDataTask *task =  [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //进行数据解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //回到主线程.( GCD)
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 通过 delegate回调
            if ([delegate respondsToSelector:@selector(didFinishComplement:)]) {
                [delegate didFinishComplement:result];
            }
        });
    }];
    //任务执行
    [task resume];
}
@end
